// 简单的koa服务器
//require(安装模块的名称)：引入对应的模块
const Koa = require('koa')
//服务器的核心对象
const app = new Koa()
//引入路由模块
const Router = require('koa-router')
const router = new Router()

const koaBody = require('koa-body')
app.use(koaBody.default())

//引入解决跨域问题的插件（手机连接服务器）
const cors = require('koa2-cors')
app.use(cors())

//引入mongoose 
const mongoose = require('mongoose')
// 导入models
const User = require('./models/User.js')
const Hotel = require('./models/Hotel.js')
const Comment = require('./models/Comment.js')
const Dingdan = require('./models/dingdan.js')

// http://127.0.0.1:3000/regist
//用户注册功能
router.post("/regist", async (ctx, next) => {
	await next()
	let uname = ctx.request.body["uname"]
	let utel = ctx.request.body["utel"]
	let upassword = ctx.request.body["upassword"]
    let checkpassword = ctx.request.body["checkpassword"]
	let uimg = ctx.request.body["uimg"]
	let postbox = ctx.request.body["postbox"]
	let sex = ctx.request.body["sex"]
	let sign = ctx.request.body["sign"]
	if (uname == undefined || uname == '') {
		ctx.body = {msg:"用户名称不能为空",err:""}
		return
	}
	if (utel == undefined || utel == '') {
		ctx.body = {msg:"用户电话不能为空",err:""}
		return
	}
	if (upassword == undefined || upassword == '') {
		ctx.body = {msg:"用户密码不能为空",err:""}
		return
	}
    if (checkpassword == undefined || checkpassword == '' ||checkpassword != upassword) {
		ctx.body = {msg:"两次密码不一致",err:""}
		return
	}
	if (uimg == undefined || uimg == '') {
		uimg = ''
	}
	if (postbox == undefined || postbox == '') {
		postbox = ''
	}
	if (sex == undefined || sex == '') {
		sex = ''
	}
	if (sign == undefined || sign == '') {
		sign = ''
	}
	// 注册本质，存
	let result = await new User({
		uname,
		utel,
		upassword,
		uimg,
		postbox,
		sex,
		sign	
	}).save().then(() => {
		return {msg:"用户保存成功",err:""}
	}).catch(err => {
		return {msg:"用户保存不成功",err:""}
	})
	ctx.body = result
})
//用户登录功能
router.post("/userlogin", async (ctx, next) => {
	await next()
	let utel = ctx.request.body["utel"]
	let upassword = ctx.request.body["upassword"]
	if (utel == undefined || utel == '') {
		ctx.body = {msg:"用户电话不能为空"}
		return
	}
	if (upassword == undefined || upassword == '') {
		ctx.body = {msg:"用户密码不能为空"}
		return
	}
	// 去MongoDB判断改用户是否存在
	let result = await User.find({
		'utel': utel,
		'upassword': upassword
	}).then(res => {
		if (res.length > 0) {
			return {msg:"用户登录成功",err:""}
		} else {
			return {msg:"用户登录失败",err:""}
		}
	}).catch(err => {
		return {msg:"用户登录失败",err:err}
	})
	ctx.body = result
})
//用户信息查询
router.post("/queryUser",async (ctx,next) =>{
	await next()
	let _id = ctx.request.body['_id']
	let result = await User.find({_id}).then(res=>{
		return {data:res,err:""}
	}).catch(err => {
		return {msg:"查询失败",err:err}
	})
	ctx.body = result
})

// 新增酒店信息
// http://localhost:3030/addJD
router.get("/addJD",async(ctx,next)=> {
	await next();//为了防止异步执行错误
	let result = await new Hotel({
			himg:"../img/a.png",
			hname:"艺术大酒店",
			valuation:"4.5",
			address:"沾益区",
			distance:"4.5km",
			price:180,
			rooms:[
					{id:1,name:"双人间",oldeprice:200,price:180,count:5},
					{id:1,name:"单人间",oldeprice:200,price:180,count:5},
					{id:3,name:"大床房",oldeprice:250,price:230,count:5},
					{id:4,name:"钟点房",oldeprice:100,price:90,count:5},
				],
			reply:[{
					commentuname:"用户1",
					commentutel:"18894632564",
					commentContent:"很好，服务态度不错",
					value:5,
					createTime:Date.now()
				}]
		}).save().then(()=>{
		return {msg:"酒店信息保存成功",err:""}
	}).catch(err => {
		return {msg:"酒店信息保存不成功",err:err}
	})
	// 设置网页中结构的内容
	ctx.body=result
})

//根据酒店名字模糊搜索酒店信息
router.post("/searchJD",async (ctx,next) => {
	await next()
	let Hname = ctx.request.body['hname']
	if (Hname == undefined) {
			Hname = ''
		}
	let result = await Hotel.find({
				$or: [{
						hname: {
							$regex: `.*${Hname}.*`
						}
					}
				]
			})
	.then(res => {
		return {data:res,err:""}
	}).catch(err => {
		return {msg:"查询失败",err:err}
	})
	ctx.body = result
})

// 判断是否有酒店信息
router.get("/findJD",async (ctx,next) =>{
	await next();//为了防止异步执行错误
	let result = await Hotel.find().then(res => {
		if(res.length >0) {
			return res
		}
		else {return {msg:"查询失败,无酒店信息",err:err}}
	}).catch(err=>false)
	ctx.body = result
})


//用户评论增加
router.post("/addcomment",async(ctx,next) =>{
	await next()
	let hname = ctx.request.body["hname"]
	let value = ctx.request.body["value"]
	let commenttext = ctx.request.body["commenttext"]
	if (commenttext == undefined || commenttext == '') {
		ctx.body = {msg:"评论内容不能为空",err:""}
		return
	}
	// hname没有传过来，待修改-----------------------------------------------------------------
	let result = await Hotel.updateOne({hname:"艺术酒店"},{
		  $push:{'reply':{
		  			commentuname:"用户2",
		  			commentutel:"18894632564",
						value:value,
		  			commentContent:commenttext,
		  			createTime:Date.now()
		  		}}
		}).then((res) => {
			return {msg:"评论保存成功",err:""}
		}).catch(err => {
			return {msg:"评论保存不成功",err:err}
		})
		ctx.body = result
})

/*************************订单接口*********************************/
router.post("/addDingdan", async (ctx, next) => {
	await next()
	let hname = ctx.request.body["hname"]
	let uname = ctx.request.body["uname"]
	let roomid = ctx.request.body["roomid"]
	let startDate = ctx.request.body["startDate"]
	let endDate = ctx.request.body["endDate"]
	let total = ctx.request.body["total"]
	// 注册本质，存
	let result = await new Dingdan({
		hname,
		uname,
		roomid,
		startDate,
		endDate,
		total,
	}).save().then((res) => {
		return {data:res,msg:"订单信息保存成功",err:""}
	}).catch(err => {
		return {msg:"订单信息保存不成功",err:""}
	})
	ctx.body = result
})


// 下单成功后，酒店的房间数量-1
router.post("/decjdCount",async (ctx,next) =>{
	await next()
	// 酒店id值
	let _id = ctx.request.body['_id']
	let roomid = ctx.request.body['roomid']
	// 二级写法
	let result = await Hotel.findOneAndUpdate({_id:_id,'rooms.id':roomid},{$inc:{'rooms.$.count':-1}
	}).then((res)=>{
			return {msg:"酒店房间数量更新成功",err:""}
		}).catch(err => {
		return {msg:"酒店房间数量更新失败",err:err}
	})
	ctx.body = result
})

// 订单结束后，酒店的房间数量+1
router.post("/incjdCount",async (ctx,next) =>{
	await next()
	// 酒店id值
	let _id = ctx.request.body['_id']
	let roomid = ctx.request.body['roomid']
	// 二级写法
	let result = await Hotel.findOneAndUpdate({_id:_id,'rooms.id':roomid},{$inc:{'rooms.$.count':+1}
	}).then(()=>{
			return {msg:"酒店房间数量更新成功",err:""}
		}).catch(err => {
		return {msg:"酒店房间数量更新失败",err:err}
	})
	ctx.body = result
})


// 查询
router.get("/querydingdan",async (ctx,next) => {
	await next()
	let Hname = ctx.request.body['hname']
	if (Hname == undefined) {
			Hname = ''
		}
	let result = await Dingdan.find({
				$or: [{
						hname: {
							$regex: `.*${Hname}.*`
						}
					}
				]
			})
	.then(res => {
		return {data:res,err:""}
	}).catch(err => {
		return {msg:"查询失败",err:err}
	})
	ctx.body = result
})

// 根据id查询订单信息
router.get("/querydingdan/:_id",async (ctx,next) => {
	await next()
	let {_id} = ctx.params
	let result = await Dingdan.find({_id})
	.then(res => {
		return {data:res,err:""}
	}).catch(err => {
		return {msg:"查询失败",err:err}
	})
	ctx.body = result
})

//核心模块中应用路由模块
app.use(router.routes())

//开启服务的端口号
app.listen(3030,(error)=>{
	if(error) throw error
	console.log('3030端口已启动')
	mongoose.connect('mongodb://127.0.0.1:27017/hoteldb')
	console.log('mongodb启动')
})